package gsdb

import (
	"fmt"

	"gitee.com/crack007/goose/gslog"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var MysqlManager *mysqlManager

func newMysqlManager() *mysqlManager {
	return &mysqlManager{
		dbMap: make(map[string]*gorm.DB),
	}
}

type mysqlManager struct {
	dbMap map[string]*gorm.DB
}

func (x *mysqlManager) init(configMap map[string]*MysqlConfig) {
	for nodeName, mysqlConfig := range configMap {
		x.initNode(nodeName, mysqlConfig)
	}
	gslog.Info("mysql init success!")
}

func (x *mysqlManager) initNode(nodeName string, config *MysqlConfig) {
	gslog.Debug("load mysql: %s", nodeName)
	var err error
	var url string
	if config.Dsn != "" {
		url = config.Dsn
	} else {
		url = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s",
			config.User,
			config.Password,
			config.Host,
			config.Port,
			config.Database,
			config.Params,
		)
	}

	gslog.Debug("connect mysql: %s", url)
	db, err := gorm.Open(mysql.Open(url), &gorm.Config{
		Logger: logger.Discard,
	})
	if err != nil {
		panic(err)
	}

	sqlDb, err := db.DB()
	if err != nil {
		panic(err)
	}

	sqlDb.SetMaxIdleConns(config.MaxIdleConnections)
	sqlDb.SetMaxOpenConns(config.MaxOpenConnections)
	if config.ShowLog {
		x.dbMap[nodeName] = db.Debug()
	} else {
		x.dbMap[nodeName] = db
	}
}
